from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from comment.models import Comment
from notifications.signals import notify
from django.utils.html import strip_tags
from notifications.models import Notification
from django.contrib.contenttypes.models import ContentType

#发送站内评论，回复等通知
@receiver(post_save, sender=Comment)
def send_comment_notification(sender, instance, **kwargs):
    # 发送站内消息
    if instance.reply_to is None:
        # 评论
        recipient = instance.content_object.get_user()
        # 评论心情
        if instance.content_type.model == 'mood':
            mood = instance.content_object  # 拿到指定心情对象
            verb = '{0} 评论了你的心情《{1}》'.format(instance.user.username, mood.intro)
        elif instance.content_type.model == 'blog':
            # 评论文章
            pass

        else:
            raise Exception('unkown comment object type')
    else:
        # 回复
        recipient = instance.reply_to
        verb = '{0} 回复了你的评论“{1}”'.format(
                instance.user.username,
                strip_tags(instance.parent.body)
            )
    # print('{0},{1},{2}, {3}'.format(instance.user, recipient, verb, instance))

    url = instance.content_object.get_url() + "#comment_elem_" + str(instance.pk)
    notify.send(instance.user, recipient=recipient, verb=verb, action_object=instance, target=None, url=url)

# 评论删除了，删除对应消息通知
@receiver(post_delete, sender=Comment)
def del_comment_notification(sender, instance, **kwargs):
    content_type = ContentType.objects.get_for_model(instance)
    print("评论删除了{0}:{1}".format(instance.id, instance.body))
    notification = Notification.objects.filter(action_object_content_type=content_type,
                                               action_object_object_id=instance.id
                                               ).first()
    notification.delete()


